package com.ddddddl.zhangben.util;

import static java.util.Calendar.*;

import java.util.Calendar;

public class CalendarUtils {
	
	public static boolean isSameWeek(Calendar calendar1, Calendar calendar2) {
		calendar1.setFirstDayOfWeek(MONDAY);
		calendar2.setFirstDayOfWeek(MONDAY);
		int year1 = calendar1.get(YEAR);
		int year2 = calendar2.get(YEAR);
		if (year1 == year2) {
			return calendar1.get(WEEK_OF_YEAR) == calendar2.get(WEEK_OF_YEAR);
		} else if (year1 - year2 == 1 && calendar2.get(Calendar.MONTH) == 11) {
			return calendar1.get(WEEK_OF_YEAR) == calendar2.get(WEEK_OF_YEAR);
		} else if (year1 - year2 == -1 && calendar1.get(Calendar.MONTH) == 11) {
			return calendar1.get(WEEK_OF_YEAR) == calendar2.get(WEEK_OF_YEAR);
		}
		return false;
	}
	
	public static boolean isSameMonth(Calendar calendar1, Calendar calendar2) {
		return calendar1.get(YEAR) == calendar2.get(YEAR) && calendar1.get(MONTH) == calendar2.get(MONTH);
	}

	public static boolean isSameDay(Calendar calendar1, Calendar calendar2) {
		return calendar1.get(YEAR) == calendar2.get(YEAR) && calendar1.get(MONTH) == calendar2.get(MONTH) && calendar1.get(DAY_OF_MONTH) == calendar2.get(DAY_OF_MONTH);
	}

	public static int getDataDiff(Calendar calendar1, Calendar calendar2) {
		int days = calendar1.get(Calendar.DAY_OF_YEAR) - calendar2.get(Calendar.DAY_OF_YEAR);
		  
		while (calendar1.get(Calendar.YEAR) < calendar2.get(Calendar.YEAR)) {
			days = calendar1.getActualMaximum(Calendar.DAY_OF_YEAR);
			calendar1.add(Calendar.YEAR, 1);
		}
		return days;
	}
	
	public static CharSequence format(int year, int month, int day) {
		return new StringBuilder()
		        .append(year).append("-")
		        .append(month < 9 ? "0" : "")
		        // Month is 0 based so add 1
		        .append(month + 1).append("-")
		        .append(day < 10 ? "0" : "")
		        .append(day);
	}
}
